#region Copyright & License
/* Tyng.Data
 * Copyright (c) 2007, Paul Tyng, All rights reserved.
 * Code licensed under the BSD License:
 * http://www.opensource.org/licenses/bsd-license.php
 * Downloaded from: http://code.google.com/p/tyngdata/
*/
#endregion

using System;
using System.Data;

namespace Tyng.Data
{
    /// <summary>
    /// Helper class for DataReaders
    /// </summary>
    public static class DataReaderHelper
    {
        /// <summary>
        /// Looks for Ordinal without throwing IndexOutOfRangeException if not found, just returns -1.
        /// </summary>
        /// <param name="dr">Data reader to search for field</param>
        /// <param name="name">Field name</param>
        /// <returns>Index of field, or -1 if not found</returns>
        public static int GetOrdinal(IDataReader dr, string name)
        {
            if (dr == null) throw new ArgumentNullException("dr");
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");

            int fieldCount = dr.FieldCount;

            if (fieldCount <= 0)
                return -1;

            for (int i = 0; i < fieldCount; i++)
            {
                if (string.Equals(name, dr.GetName(i), StringComparison.OrdinalIgnoreCase))
                    return i;
            }

            return -1;
        }

		/// <summary>
		/// Reads a IDataReader field into a byte array
		/// </summary>
		/// <param name="dr">Data reader</param>
		/// <param name="ordinal">index of the field to read</param>
		/// <returns>byte array</returns>
		public static byte[] GetBytes(IDataReader dr, int ordinal)
		{
			long len = dr.GetBytes(ordinal, 0, null, 0, int.MaxValue); // gets the length
			byte[] b = new byte[len]; // initialize buffer
			dr.GetBytes(ordinal, 0, b, 0, b.Length); // reads the data
			return b;
		}
    }
}
